package distributed.controller;

import org.w3c.dom.NamedNodeMap;

import distributed.entity.Event;
import distributed.entity.EventModel;
import distributed.entity.User;

import server.ClientState;
import server.Server;
import xml.Message;

/**
 * Controller to handle adding a choice to a given event
 * @author Marcus Menghini, Patrick Feeney
 *
 */
public class AddChoiceController implements IProtocolController{

	/** Processes a message from a client */
	public Message process(ClientState state, Message request) {
		String xmlString;
		
		NamedNodeMap map = request.contents.getFirstChild().getAttributes(); //Grab the attributes
		
		String id = map.getNamedItem("id").getNodeValue(); //Get the id data
		String choice = map.getNamedItem("choice").getNodeValue(); //Get the choice name
		int index = Integer.decode(map.getNamedItem("number").getNodeValue()); //Get its location
		
		Event event = EventModel.getInstance().getEvent(id); //Grab our event
		
		if (event.setChoice(index, choice)){ // Try and set the choice
			xmlString = Message.responseHeader(request.id()) + "<addChoiceResponse id='" +
					id + "' number='" + index + "' choice=\"" + choice + "\"/></response>";
		}
		else { //If it failed, let us know and return
			xmlString = Message.responseHeader(request.id(), "This choice is already present") + 
			"<addChoiceResponse id='" + id + "' number='" + index + "' choice=\"" 
			+ choice + "\"/></response>";
			
			return new Message(xmlString);
		}
		
		Message send = new Message(xmlString);
		// Construct the message and send it to everyone except the originator
		for (User u : event.getUsers())
			if (u != null && !u.getID().equals(state.id()))
				if (Server.getState(u.getID()) != null)
					Server.getState(u.getID()).sendMessage(send);
		
		if (event.isStart()) { //If we just started the event (closed w/ <max choices, last filled)
			xmlString = Message.responseHeader(request.id()) + "<closeResponse/></response>";
			// Send the originator the message back
			state.sendMessage(send);
			
			send = new Message(xmlString);
			// Make a closeResponse message and send it to everyone
			for (User u : event.getUsers())
				if (u != null && !u.getID().equals(state.id()))
					Server.getState(u.getID()).sendMessage(send);
			
			Message close = new Message(Message.responseHeader(request.id()) + 
					"<turnResponse/></response>");
			// Tell the moderator to start
			Server.getState(event.getUsers()[0].getID()).sendMessage(close);
		}
		//Return the message
		return send;
	}
	
	/**
	 * @return AddChoiceController
	 */
	public IProtocolController newCopy() {
		return new AddChoiceController();
	}

}
